package com.xinxin.blockchain.asset.strategy;

import com.xinxin.blockchain.asset.exception.AssetShortageException;
import com.xinxin.blockchain.model.AccountAsset;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * 资产消耗
 * 可用 减少
 * 冻结 不变
 * 总额 减少
 *
 * @author ys
 * @date 2021/5/24
 */
@Component
public class AssetCostOperateStrategy extends AssetOperateStrategy {

    @Override
    public boolean operate(AccountAsset asset, BigDecimal amount) throws AssetShortageException {
        if (amount.compareTo(asset.getAvailable()) > 0) {
            throw new AssetShortageException("资产消耗，可用不足");
        }

        AccountAsset update = new AccountAsset()
                .setId(asset.getId())
                .setVersion(asset.getVersion())
                .setAvailable(asset.getAvailable().subtract(amount))
                .setTotal(asset.getTotal().subtract(amount));
        return accountAssetService.optimisticLockUpdate(update);
    }
}
